//
//  MyMaterials.swift
//  ElectricStationBoard
//
//  Created by Galaxy on 16/7/5.
//  Copyright © 2016年 Iris. All rights reserved.
//

import UIKit
import AVFoundation
import Photos

class MyMaterials: UITableViewController,UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate {
    
    //单元格里显示头像
    var img:UIImageView!
    var sourceType = UIImagePickerControllerSourceType.PhotoLibrary;//将sourceType赋一个初始类型,防止调用时不赋值出现崩溃
    var optionMenu:UIAlertController!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的资料";
        self.navigationController?.navigationBarHidden = false;
        self.tableView.scrollEnabled = false;
        let footerView = UIView();
        footerView.backgroundColor = UIColor.clearColor();
        (view as? UITableView)?.tableFooterView = footerView;
        
        //设置显示头像的ImageView的大小
        img = UIImageView(frame:CGRectMake(200, 0, 30, 30));
        

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        
        return 1;
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 2;
    }

   
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let reuseIdentifier = "reuseIdentifier";
        var cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier);
        if cell == nil {
            cell = UITableViewCell(style:.Default, reuseIdentifier: reuseIdentifier);
        }

        // Configure the cell...
        switch indexPath.row {
        case 0:
            cell!.textLabel?.text = "头像";
            cell!.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator;
            cell!.contentView.addSubview(img);
        case 1:
            cell!.textLabel?.text = "手机号";
        default:
            "Default";
        }

        return cell!
    }
  
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        switch indexPath.row {
        case 0:
            self.actionSheet();
        default:
            "Default";
            
        }
    }
    
    func actionSheet() -> Void {
        if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) && UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) {
        optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet);
        let shotAction = UIAlertAction(title: "拍照", style: .Default, handler: {(alert:UIAlertAction!) -> Void in
            //print("拍照上传");
            if(self.cameraPermisson() == true) {
                self.sourceType = UIImagePickerControllerSourceType.Camera;
                self.open();
            }else {
                self.optionMenu = UIAlertController(title: nil, message: "请在设置中打开摄像头权限", preferredStyle: .Alert);
                let tempAction = UIAlertAction(title: "确定", style: .Cancel, handler: { (alert:UIAlertAction) in
                    print("取消打开摄像头")
                    
                })
                self.optionMenu.addAction(tempAction);
                self.presentViewController(self.optionMenu, animated: true, completion: nil);
            }
        });
        let picInAlbum = UIAlertAction(title: "从相册中选择", style: .Default, handler: {(alert:UIAlertAction!) -> Void in
            print("从相册中选择图片");
            if(self.photoLibraryPermission() == true) {
                self.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
                self.open();
            } else {
                self.optionMenu = UIAlertController(title: nil, message: "请在设置中打开相册权限", preferredStyle: .Alert);
                let tempAction = UIAlertAction(title: "确定", style: .Cancel, handler: { (alert:UIAlertAction!) in
                    print("取消")
                })
                self.optionMenu.addAction(tempAction);
                self.presentViewController(self.optionMenu, animated: true, completion: nil)
                
                
            }
        });
        
        let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: {(alert:UIAlertAction!) -> Void in
            print("取消")
        });
        optionMenu.addAction(shotAction);
        optionMenu.addAction(picInAlbum);
        optionMenu.addAction(cancelAction);
        self.presentViewController(optionMenu, animated: true, completion: nil)
        
        
        }}
    
    //打开图库或相机
    func open() {
        let imagePickerController:UIImagePickerController = UIImagePickerController();
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = true //为拍照,选择完进入图片编辑模式
        imagePickerController.sourceType = sourceType;
        self.presentViewController(imagePickerController, animated: true, completion: {});
        
    }
    
    //判断相机权限
    func cameraPermisson() -> Bool {
        let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo);
        if (authStatus == AVAuthorizationStatus.Denied || authStatus == AVAuthorizationStatus.Restricted) {
            return false;
        } else {
            return true;
        }
    }
    
    //判断相册权限
    func photoLibraryPermission() -> Bool {
        let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
        if (library == PHAuthorizationStatus.Denied || library == PHAuthorizationStatus.Restricted) {
            return false;
        }else{
            return true;
        }
    }
    
    //    取消图片选择操作
    func imagePickerControllerDidCancel(picker:UIImagePickerController)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    //    选择完图片操作
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!,editingInfo: [NSObject : AnyObject]!) {
        img.image = image
        let imageData = UIImageJPEGRepresentation(image, 0.6);
        let userDefault = NSUserDefaults.standardUserDefaults();
        userDefault.setObject(imageData, forKey: "userPhoto");
        
        
        
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
